from typing import List


def format_doc(doc: str, space_line: bool = True) -> str:
    """ 格式化 python 方法的文档注释

    ---

    在这个项目中用于去掉方法注释的多余前缀空格

    ### Args:

    - doc: 原始文档字符串

    ### Example:

    >>> format_doc(print.__doc__)
    """
    min_prefix = 99999
    doc = doc.strip().replace("\t", "    ")
    line_list = doc.splitlines()

    start = True
    for line in line_list:
        if not line.strip():
            continue
        if start:
            start = False
            continue
        prefix = 0
        for c in line:
            if c == ' ':
                prefix += 1
            else:
                break
        if prefix < min_prefix:
            min_prefix = prefix

    result: List[str] = []
    for line in line_list:
        if not space_line and not line.strip():
            continue
        result.append(line.replace(' ', '', min_prefix))

    return '\n'.join(result)


def parse(source: str) -> List[str]:
    result: List[str] = []

    instr: bool = False
    enter_start_limit: str = ''
    buf: str = ''

    for c in source:
        if instr:
            if c == enter_start_limit:
                instr = False
                result.append(buf)
                buf = ''
                continue
            buf += c
        else:
            if c in '\'\"`':
                if buf:
                    raise Exception(f"字符串前面出现了多余的 {buf}")
                instr = True
                enter_start_limit = c
                continue
            if c == ' ':
                if buf:
                    result.append(buf)
                    buf = ''
                    continue
            buf += c
    if buf:
        result.append(buf)

    return result
